package com.qk.management.service;

import com.qk.common.constants.AvatarMessageConstants;
import com.qk.common.event.CleanupCompletedEvent;
import com.qk.common.event.EventPublisher;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

@Slf4j
public abstract class AbstractCleanupService<T> {

    protected abstract List<T> findExpiredItems();
    protected abstract void cleanupItem(T item) throws Exception;
    protected abstract void handleCleanupError(T item, Exception e);
    protected abstract void deleteRecords(List<T> items);
    protected abstract String getTargetType();
    public void performCleanup() {
        log.info(AvatarMessageConstants.CLEANUP_TASK_STARTED);
        try {
            List<T> expiredItems = findExpiredItems();
            log.info(AvatarMessageConstants.CLEANUP_TASK_FOUND_ITEMS, expiredItems.size());
            
            int successCount = 0;
            int failCount = 0;
            
            for (T item : expiredItems) {
                try {
                    cleanupItem(item);
                    successCount++;
                } catch (Exception e) {
                    handleCleanupError(item, e);
                    failCount++;
                }
            }
            
            deleteRecords(expiredItems);
            CleanupCompletedEvent<T> event = new CleanupCompletedEvent<>(
                expiredItems, successCount, failCount, getTargetType());
            EventPublisher.publish(event);
            
            log.info("{}，{}: {}，{}: {}", AvatarMessageConstants.CLEANUP_TASK_COMPLETED, AvatarMessageConstants.CLEANUP_TASK_SUCCESS, successCount, AvatarMessageConstants.CLEANUP_TASK_FAILURE, failCount);
        } catch (Exception e) {
            log.error(AvatarMessageConstants.CLEANUP_TASK_ERROR, e);
        }
    }
}